package net;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Author Justin Parker
 * @Date 2024/7/18 0018 17:32
 * @Version 1.0
 */
public class ChatClient02 {
    private Socket socket;
    public ChatClient02(){
        try{
            System.out.println("客户端启动.....");
            socket = new Socket("localhost",8088);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void start(){
        Scanner sc =null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try{
            //获取输出流对象，能够一次写一行
            pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(
                                    socket.getOutputStream(), StandardCharsets.UTF_8)),true);

            //2.读写数据
            //启动新的进程，读取服务端的数据
            new Thread(new ServerHandler()).start();
            //构建Scanner负责读取键盘数据写入到服务器
            sc = new Scanner(System.in);
            System.out.println("请输入数据：");
            while (true) {
                String line = sc.nextLine();//这个方法是阻塞式方法，，没有输入就会在这里阻塞
                if ("exit".equalsIgnoreCase(line)) break;
                pw.println(line);

                }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //3.释放资源
            if (sc != null) sc.close();
            if (pw != null) pw.close();
            if (socket != null)
               try {
                   socket.close();
               }catch (IOException e){
                   e.printStackTrace();
               }
        }
    }

    //构建客户端任务类型，负责处理服务端返回的数据
    private  class ServerHandler implements Runnable{
        public void run(){
         BufferedReader br = null;
         try {
             br = new BufferedReader(
                     new InputStreamReader(
                             socket.getInputStream(), StandardCharsets.UTF_8));

             String line = null;
             while ((line=br.readLine())!=null){
                System.out.println(line);}
         }catch (IOException e){
             e.printStackTrace();
         }
        }
    }
    public static void main(String[] args){

       new ChatClient02().start();
    }
}
